package com.sbs.gaoxinqutoilet.fragment;

import android.os.Bundle;
import android.os.Handler;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.Nullable;
import androidx.appcompat.widget.Toolbar;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.lcodecore.tkrefreshlayout.RefreshListenerAdapter;
import com.lcodecore.tkrefreshlayout.TwinklingRefreshLayout;
import com.lcodecore.tkrefreshlayout.footer.LoadingView;
import com.lcodecore.tkrefreshlayout.header.SinaRefreshView;
import com.sbs.gaoxinqutoilet.R;
import com.sbs.gaoxinqutoilet.adapter.ToiletTongjiRvAdapter;
import com.sbs.gaoxinqutoilet.base.BaseBackFragment;
import com.sbs.gaoxinqutoilet.entity.HomeMenuEntity;
import com.sbs.gaoxinqutoilet.entity.TongjiEntity;
import com.sbs.gaoxinqutoilet.eventbus.EventCenter;
import com.sbs.gaoxinqutoilet.http.HttpApis;
import com.sbs.gaoxinqutoilet.http.Request;
import com.sbs.gaoxinqutoilet.interfaces.Constant;
import com.sbs.gaoxinqutoilet.interfaces.EventConstant;
import com.sbs.gaoxinqutoilet.utils.GsonTools;
import com.sbs.gaoxinqutoilet.utils.HttpUtils;
import com.sbs.gaoxinqutoilet.utils.LogUtils;
import com.sbs.gaoxinqutoilet.utils.NetworkUtils;
import com.zhy.autolayout.AutoRelativeLayout;
import com.zhy.http.okhttp.OkHttpUtils;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;

import java.util.ArrayList;
import java.util.HashMap;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.Unbinder;

/**
 * Created by 聪明一只哈 on 2018/6/25.
 * Time: 2018/6/25  16:56
 */

public class ToiletStatisTicalFragmentC extends BaseBackFragment {

    //传过来的改造档案数据  存储在Bundle中
    private static final String STATISTICAL_FILE = "statistical_file";
    @BindView(R.id.toolbar_back)
    ImageView toolbarBack;
    @BindView(R.id.toolbar_title)
    TextView toolbarTitle;
    @BindView(R.id.toolbar_iv_menu)
    ImageView toolbarIvMenu;
    @BindView(R.id.toolbar_tv_menu)
    TextView toolbarTvMenu;
    @BindView(R.id.toolbar_rl_menu)
    AutoRelativeLayout toolbarRlMenu;
    @BindView(R.id.tongji_trefresh)
    TwinklingRefreshLayout tongjiTrefresh;
    @BindView(R.id.tongji_rv)
    RecyclerView tongjiRv;
    @BindView(R.id.toolbar)
    Toolbar toolbar;
    Unbinder unbinder;
    private HomeMenuEntity homemenu_buildfile;
    private ToiletTongjiRvAdapter applyRvAdapter;
    private View emptyView;
    private View errorView;
    private View footView;

    private ArrayList<TongjiEntity.DataBean> buyItemList;

    private int pageSize = 5;
    private int index;


    public static ToiletStatisTicalFragmentC newInstance(HomeMenuEntity homeMenuEntity) {
        Bundle args = new Bundle();
        args.putSerializable(STATISTICAL_FILE, homeMenuEntity);
        ToiletStatisTicalFragmentC fragment = new ToiletStatisTicalFragmentC();
        fragment.setArguments(args);
        return fragment;
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_statisticalc, container, false);
        unbinder = ButterKnife.bind(this, view);
        initView(inflater);
        initListener();

        return attachToSwipeBack(view);
    }


    private void initView(LayoutInflater inflater) {
        EventBus.getDefault().register(this);
        toolbarTitle.setText("改厕进度统计");
        //返回按钮
        toolbarBack.setVisibility(View.VISIBLE);
        //设置回键
        initToolbarBack(toolbar);



        //获取传递过来的值
        Bundle arguments = getArguments();
        if (arguments != null) {
            homemenu_buildfile = (HomeMenuEntity) arguments.getSerializable(STATISTICAL_FILE);
            if (homemenu_buildfile != null) {
                Log.i("统计页面", "initView: " + homemenu_buildfile.getFunc_name() + "~~~" + homemenu_buildfile.getFunc_id());
                //showShortToast(homemenu_buildfile.getFunc_name()+"~~~"+homemenu_buildfile.getFunc_id());
            }

        }

        //添加刷新头和尾
        SinaRefreshView sinaHeader = new SinaRefreshView(_mActivity);
        sinaHeader.setArrowResource(R.drawable.arrow);
        sinaHeader.setTextColor(0xff745D5C);
        tongjiTrefresh.setHeaderView(sinaHeader);

        LoadingView loadingView = new LoadingView(_mActivity);
        tongjiTrefresh.setBottomView(loadingView);
        //设置是否禁用上下拉
        tongjiTrefresh.setEnableLoadmore(false);

        //初始化index
        index = 0;
        applyRvAdapter = new ToiletTongjiRvAdapter(R.layout.item_toilet_tongji, buyItemList);
        tongjiRv.setLayoutManager(new LinearLayoutManager(_mActivity));
        tongjiRv.setAdapter(applyRvAdapter);
        //默认第一次加载会进入回调
        applyRvAdapter.disableLoadMoreIfNotFullPage(tongjiRv);
        // TODO: 2018/6/16
//        applyRvAdapter.setHeaderAndEmpty(true);
//        applyRvAdapter.setHeaderFooterEmpty(true,true);

        emptyView = inflater.inflate(R.layout.view_empty, tongjiRv, false);
        errorView = inflater.inflate(R.layout.view_error, tongjiRv, false);
        footView = inflater.inflate(R.layout.view_foot, tongjiRv, false);

    }


    private void initListener() {

        tongjiTrefresh.setOnRefreshListener(new RefreshListenerAdapter() {
            //正在刷新
            @Override
            public void onRefresh(TwinklingRefreshLayout refreshLayout) {
                super.onRefresh(refreshLayout);
                //设置时长
                new Handler().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        Log.i("显示", "refreshRun");

                        requestRefresh();
                    }
                }, 2000);
            }

            //刷新完成
            @Override
            public void onFinishRefresh() {
                super.onFinishRefresh();
                Log.i("显示", "Finishrefresh");
                //打开或关闭加载（一般用于下拉的时候做处理，因为上拉下拉不能同时操作）
                applyRvAdapter.setEnableLoadMore(true);

            }
        });
        //预加载
        applyRvAdapter.setPreLoadNumber(Constant.PRE_SIZE);
        //设置动画
        applyRvAdapter.openLoadAnimation(BaseQuickAdapter.SCALEIN);

        //applyRvAdapter加载数据的监听
        //https://www.jianshu.com/p/b343fcff51b0
        //加载完成（注意不是加载结束，而是本次数据加载结束并且还有下页数据）
        //mQuickAdapter.loadMoreComplete();
        //加载失败
        //mQuickAdapter.loadMoreFail();
        //加载结束
        //mQuickAdapter.loadMoreEnd();
        applyRvAdapter.setOnLoadMoreListener(new BaseQuickAdapter.RequestLoadMoreListener() {
            @Override
            public void onLoadMoreRequested() {
                int currentSize = applyRvAdapter.getData().size();
                if (!TextUtils.isEmpty(mTotalSize)) {

                    int totalSize = Integer.parseInt(mTotalSize);
                    if (currentSize >= totalSize) {
                        applyRvAdapter.loadMoreEnd();
                    } else {
                        index++;


                            Log.i("页数和列表数", "加载中: index:"
                                    + index + "~~pagesize:" + pageSize
                                    + "~~totalSize:" + totalSize
                                    + "~~currentSize:" + currentSize);
                            loadMoreData(index * pageSize, pageSize);



                    }
                }

            }
        }, tongjiRv);


    }


    /**
     * eventbus 页面跳转,事件接受
     *
     * @param center
     */
    @Subscribe
    public void onEventReceive(EventCenter center) {

        if (center.getEventCode() == EventConstant.UPLOAD_BUY_MODIFY) {
            //提交成功
            LogUtils.e("显示", "刷新");
            new Handler() {
            }.postDelayed(new Runnable() {
                @Override
                public void run() {
                    // requestRefresh();
                }
            }, 500);
        }
    }

    /**
     * 页面加载动画结束就调用  loadMoreData(index, pageSize);
     * 所以  将两个方法紧挨着
     *
     * @param savedInstanceState
     */
    @Override
    public void onEnterAnimationEnd(Bundle savedInstanceState) {
        super.onEnterAnimationEnd(savedInstanceState);
        //添加家在逻辑
        requestRefresh();

        loadMoreData(index, pageSize);

    }

    private void requestRefresh() {

        //设置出现刷新状态的头部
        if (tongjiTrefresh != null) {
            tongjiTrefresh.finishRefreshing();
        }
        index = 0;

        loadMoreData(index, pageSize);
    }



    private void loadMoreData(int indexs, int pageSize) {

        String tongji_Url = HttpApis.tongjiDate;


        HashMap<String, String> params = new HashMap<>();
        params.put("iud", homemenu_buildfile.getIud());
        params.put("start", String.valueOf(indexs));
        params.put("pagesize", String.valueOf(pageSize));

        HttpUtils.requestGet(_mActivity, tongji_Url,params, new Request(){
            @Override
            public void success(String jsonStr) {
                super.success(jsonStr);

                Log.i("buildfile_success", jsonStr);


                TongjiEntity tongjiEntity = GsonTools.changeGsonToBean(jsonStr, TongjiEntity.class);

                processSetData(tongjiEntity);

                applyRvAdapter.loadMoreComplete();

                if (index == 0) {
                    cancelLoadingDialog();
                }


            }

            @Override
            public void error(String error) {
                super.error(error);
                Log.i("buildfile_error", error);

                if (!NetworkUtils.isConnected(_mActivity)) {
                    applyRvAdapter.setEmptyView(errorView);
                } else {
                    applyRvAdapter.setEmptyView(emptyView);
                    applyRvAdapter.loadMoreFail();
                }


                cancelLoadingDialog();
            }

        });

    }

    private String mTotalSize;
    private void processSetData(TongjiEntity buildFileItemEntity) {

        if (buildFileItemEntity != null) {

            mTotalSize = buildFileItemEntity.getRecordsTotal();
            if (Integer.parseInt(mTotalSize) > 0) {
                if (index == 0) {
                    //设置新数据
                    applyRvAdapter.setNewData(buildFileItemEntity.getData());
                } else {
                    applyRvAdapter.addData(buildFileItemEntity.getData());
                }
            } else {
                applyRvAdapter.setEmptyView(emptyView);
            }
        } else {
            applyRvAdapter.setEmptyView(emptyView);
        }
    }



    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
        EventBus.getDefault().unregister(this);
        OkHttpUtils.getInstance().cancelTag(this);
        cancelLoadingDialog();
    }
}
